package com.iterator.service.web.systemManager;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import com.iterator.bean.web.pojo.lyh.MallUserExample;
import com.iterator.bean.web.pojo.lyh.User;
import com.iterator.bean.wechat.dhy.WxRegisterBO;
import com.iterator.bean.wechat.dhy.WxUserLoginVO;

import com.iterator.bean.web.dhy.RoleAddPermissionsBO;
import com.iterator.bean.web.dhy.RolePermissionsVO;
import com.iterator.bean.web.pojo.dhy.*;
import com.iterator.bean.web.dhy.RoleListVO;
import com.iterator.bean.web.dhy.RoleVO;
import com.iterator.mapper.web.marketManager.RoleThreeLevelMapper;
import com.iterator.mapper.web.systemManager.AdminMapper;
import com.iterator.mapper.web.systemManager.CskaoyanmallRoleMapper;
import com.iterator.mapper.web.systemManager.RoleOneLevelMapper;
import com.iterator.mapper.web.systemManager.RoleTwoLevelMapper;

import com.iterator.mapper.web.userManager.MallUserMapper;
import com.iterator.util.IteratorEncrypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @Author: DHY
 * @Date: 2021/1/9 20:01
 * @Description:
 */
@Service
public class SystemManageServiceImpl implements SystemManageService {
    @Autowired
    CskaoyanmallRoleMapper roleMapper;
    @Autowired
    RoleThreeLevelMapper roleThreeLevelMapper;
    @Autowired
    RoleTwoLevelMapper roleTwoLevelMapper;
    @Autowired
    RoleOneLevelMapper roleOneLevelMapper;

    @Autowired
    AdminMapper adminMapper;
    @Autowired
    MallUserMapper userMapper;


    /**
     * 创建角色
     */
    @Override
    public RoleVO roleCreate(String desc, String name) {
        //判断用户是否存在
        CskaoyanmallRoleExample cskaoyanmallRoleExample = new CskaoyanmallRoleExample();
        CskaoyanmallRoleExample.Criteria criteria = cskaoyanmallRoleExample.createCriteria();
        if (name != null || name.length() != 0) {
            criteria.andNameEqualTo(name);
        }
        long l = roleMapper.countByExample(cskaoyanmallRoleExample);
        if (l!=0){
            return null;
        }


        CskaoyanmallRole role = new CskaoyanmallRole(null, name, desc, true, new Date(), new Date(), false);
        //添加信息
        roleMapper.insertInfo(role);
        //查询添加的信息
        CskaoyanmallRole role1 = roleMapper.selectByPrimaryKey(role.getId());
        return new RoleVO(role1.getId(), role1.getName(), role1.getDesc(),role1.getAddTime(),role1.getUpdateTime(),null,null);

    }

    /**
     * 角色管理页面显示
     *
     * @param page
     * @param limit
     * @param sort
     * @param order
     * @return
     */
    @Override
    public RoleListVO showList(Integer page, Integer limit, String sort, String order, String name) {
        //分页
        PageHelper.startPage(page, limit);
        CskaoyanmallRoleExample roleExample = new CskaoyanmallRoleExample();
        //排序
        roleExample.setOrderByClause(sort +" "+ order);
        CskaoyanmallRoleExample.Criteria criteria = roleExample.createCriteria();
        //模糊查询
        if (name != null && name.length() != 0) {
            //忽略输入的空格
            String s = name.replaceAll(" ", "");
            criteria.andNameLike("%" + s + "%");
        }
        //查询结果
        List<CskaoyanmallRole> roles = roleMapper.selectByExample(roleExample);
        //封装
        PageInfo<CskaoyanmallRole> rolePageInfo = new PageInfo<>(roles);
        int total = (int) rolePageInfo.getTotal();
        List<RoleVO> roleVO = new ArrayList<>();
        for (CskaoyanmallRole role : roles) {
            roleVO.add(new RoleVO(role.getId(), role.getName(), role.getDesc(),
                    role.getAddTime(), role.getUpdateTime(), role.getEnabled(), role.getDeleted()));
        }
        //返回

        return new RoleListVO(total, roleVO);
    }

    /**
     * 删除角色
     *
     * @param id
     */
    @Override
    public void roleDelete(Integer id) {
        roleMapper.deleteByPrimaryKey(id);
    }

    /**
     * 修改角色信息
     *
     * @param id
     * @param name
     * @param desc
     * @param updateTime
     */
    @Override
    public void roleUpdate(Integer id, String name, String desc, Date updateTime) {
        CskaoyanmallRole role = new CskaoyanmallRole();
        role.setId(id);
        role.setName(name);
        role.setDesc(desc);
        role.setUpdateTime(updateTime);
        roleMapper.updateByPrimaryKeySelective(role);
    }

    /**
     * 角色授权页面显示
     *
     * @param id
     * @return
     */
    @Override
    public RolePermissionsVO rolePerMissions(Integer id) {
        RolePermissionsVO permissionsVO = new RolePermissionsVO();

        //封装assignedPermissions list
        //查询关系表
        List<String> list= roleThreeLevelMapper.selectThreeLevelIdByRoleId(id);
        permissionsVO.setAssignedPermissions(list);



        //封装systemPermissions list

        //查询第一张表中所有的值
        RoleOneLevelExample roleOneLevelExample = new RoleOneLevelExample();
        List<RoleOneLevel> roleOneLevels = roleOneLevelMapper.selectByExample(roleOneLevelExample);
        List<RolePermissionsVO.SystemPermissionsBean> systemPermissionsBeans = new ArrayList<>();
        for (RoleOneLevel roleOneLevel : roleOneLevels) {
            //第一层
            RolePermissionsVO.SystemPermissionsBean systemPermissionsBean = new RolePermissionsVO.SystemPermissionsBean();
            //封装第一层里的值
            systemPermissionsBean.setId(roleOneLevel.getId());
            systemPermissionsBean.setLabel(roleOneLevel.getLabel());

            //根据第一张表的id 查询第二张表中所有的值
            RoleTwoLevelExample example1 = new RoleTwoLevelExample();
            RoleTwoLevelExample.Criteria criteria1 = example1.createCriteria();
            criteria1.andOneIdEqualTo(roleOneLevel.getId());
            List<RoleTwoLevel> roleTwoLevels = roleTwoLevelMapper.selectByExample(example1);
            List<RolePermissionsVO.SystemPermissionsBean.ChildrenBeanX> childrenBeanXES = new ArrayList<>();
            for (RoleTwoLevel roleTwoLevel : roleTwoLevels) {
                //第二层
                RolePermissionsVO.SystemPermissionsBean.ChildrenBeanX childrenBeanX = new RolePermissionsVO.SystemPermissionsBean.ChildrenBeanX();
                //封装第二层里的值
                childrenBeanX.setId(roleTwoLevel.getId());
                childrenBeanX.setLabel(roleTwoLevel.getLabel());

                //根据第二张表的id 查询第三张表中所有的值
                RoleThreeLevelExample roleThreeLevelExample = new RoleThreeLevelExample();
                RoleThreeLevelExample.Criteria criteria2 = roleThreeLevelExample.createCriteria();
                criteria2.andTwoIdEqualTo(roleTwoLevel.getId());
                List<RoleThreeLevel> roleThreeLevels1 = roleThreeLevelMapper.selectByExample(roleThreeLevelExample);
                List<RolePermissionsVO.SystemPermissionsBean.ChildrenBeanX.ChildrenBean> childrenBeans = new ArrayList<>();
                for (RoleThreeLevel roleThreeLevel : roleThreeLevels1) {
                    //第三层
                    RolePermissionsVO.SystemPermissionsBean.ChildrenBeanX.ChildrenBean childrenBean = new RolePermissionsVO.SystemPermissionsBean.ChildrenBeanX.ChildrenBean();
                    //封装第三层里的值
                    childrenBean.setId(roleThreeLevel.getId());
                    childrenBean.setLabel(roleThreeLevel.getLabel());
                    childrenBean.setApi(roleThreeLevel.getApi());
                    //放入第二层的list
                    childrenBeans.add(childrenBean);
                }
                //封装第二层的list
                childrenBeanX.setChildren(childrenBeans);
                //放入第一层的list
                childrenBeanXES.add(childrenBeanX);

            }
            //封装第一层的list
            systemPermissionsBean.setChildren(childrenBeanXES);
            systemPermissionsBeans.add(systemPermissionsBean);
        }
        //封装
        permissionsVO.setSystemPermissions(systemPermissionsBeans);

        return permissionsVO;
    }

    /**
     * 添加角色权限
     * @param roleAddPermissionsBO
     */
    @Override
    public void roleAddPerMissions(RoleAddPermissionsBO roleAddPermissionsBO) {
        List<String> permissions = roleAddPermissionsBO.getPermissions();
        //删除关系表的之前与id对应的所有数据
        roleThreeLevelMapper.deleteOldInfo(roleAddPermissionsBO.getRoleId());
        //添加新的对应关系
        for (String permission : permissions) {
            roleThreeLevelMapper.insertNewInfo(permission,roleAddPermissionsBO.getRoleId());
        }
    }

    /**
     * 管理员页面显示
     * @return
     */
    @Override
    public List<Map> roleOptions() {
        List<CskaoyanmallRole> cskaoyanmallRoles = roleMapper.selectByExample(new CskaoyanmallRoleExample());
        ArrayList<Map> maps = new ArrayList<>();
        for (CskaoyanmallRole cskaoyanmallRole : cskaoyanmallRoles) {
            HashMap<Object, Object> objectObjectHashMap = new HashMap<>();
            objectObjectHashMap.put("value",cskaoyanmallRole.getId());
            objectObjectHashMap.put("label",cskaoyanmallRole.getName());
            maps.add(objectObjectHashMap);
        }
        return maps;
    }


    /**
     * 微信前台登录
     * @param username
     * @param host
     * @return
     */
    @Override
    public WxUserLoginVO login(String username, String host) {
        int i = adminMapper.updateUserLoginInfo(username, host);
        if(i != 1){
            return null;
        }
        WxUserLoginVO loginVO = adminMapper.selectLoginInfoByUsername(username);
        return loginVO;
    }

    /**
     * 用户注册
     * @param wxRegisterBO
     */
    @Override
    public int register(WxRegisterBO wxRegisterBO,String code) {
        //对比验证码
        boolean equals = wxRegisterBO.getCode().equals(code);
        if (!equals) {
            //验证码错误
            return 502;
        }
        //判断用户名是否重复
        MallUserExample mallUserExample = new MallUserExample();
        mallUserExample.createCriteria().andUsernameEqualTo(wxRegisterBO.getUsername());
        long l = userMapper.countByExample(mallUserExample);
        if (l != 0) {
            return 505;
        }
        //判断手机号是否存在
        MallUserExample mallUserExample1 = new MallUserExample();
        mallUserExample1.createCriteria().andMobileEqualTo(wxRegisterBO.getMobile());
        long l1 = userMapper.countByExample(mallUserExample1);
        if (l1 != 0) {
            return 508;
        }
        User user = new User();
        user.setAddTime(new Date());
        user.setUpdateTime(new Date());
        user.setUsername(wxRegisterBO.getUsername());
        //对密码进行加密
        String encryptPassword = IteratorEncrypt.getEncryptPassword(wxRegisterBO.getPassword());
        user.setPassword(encryptPassword);
        user.setNickname(wxRegisterBO.getUsername());
        user.setMobile(wxRegisterBO.getMobile());
        user.setWeixinOpenid(wxRegisterBO.getWxCode());
        user.setAvatar("https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif?imageView2/1/w/80/h/80");
        userMapper.insertSelective(user);
        return 200;
    }

    /**
     * 重置用户密码
     * @param code
     * @param mobile
     * @param password
     * @param newCode
     * @return
     */
    @Override
    public int resetPassword(String code, String mobile, String password, String newCode) {
        if (!code.equals(newCode)) {
            //验证码不正确
            return 502;
        }
        MallUserExample mallUserExample = new MallUserExample();
        mallUserExample.createCriteria().andMobileEqualTo(mobile);
        long l = userMapper.countByExample(mallUserExample);
        if (l == 0) {
            //手机号码不存在
            return 503;
        }
        User user = new User();
        user.setPassword(password);
        user.setUpdateTime(new Date());
        userMapper.updateByExampleSelective(user,mallUserExample);
        return 200;
    }

    /**
     * vx 登录的时候判断是用户名还是手机号
     * @param username
     * @return
     */
    @Override
    public String judgeUserName(String username) {
        MallUserExample mallUserExample = new MallUserExample();
        mallUserExample.createCriteria().andUsernameEqualTo(username);
        long l = userMapper.countByExample(mallUserExample);
        if (l != 0) {
            //输入的是用户名
            return username;
        }
        //输入的可能是手机号,也可能输入的用户名不存在
        try {
            long l1 = Long.parseLong(username);
            //通过手机号查询userName
            MallUserExample mallUserExample1 = new MallUserExample();
            mallUserExample1.createCriteria().andMobileEqualTo(username);
            List<User> users = userMapper.selectByExample(mallUserExample1);
            if (users != null && users.size() != 0) {
                //查询到了userName
                User user = users.get(0);
                return user.getUsername();
            }
        } catch (NumberFormatException e) {
            //不是数字,返回userName
        }
        return username;

    }
}
